import QuLe, { ADType } from "../QuLe";
import { JSBridge } from "../JSBridge";
import ADBase, { BannerPos } from "../ADBase";
import SDKManager, { MaxCloseBannerTimes } from "../SDKManager";
import { TouTiaoConfig } from "./TouTiaoConfig";

export default class TouTiaoAD extends ADBase {

    //Banner
    bannerAdWidth = 120;
    bannerAd: any;
    //激励视频
    videoAd: any;
    isListenVideoShow = false;
    onVideoClose: Function;
    //插屏广告
    insertAD: any;
    onInsertADClose: Function;

    /** 开始显示Banner广告//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     * @param position 显示位置
     * @param loadNewAD 是否切换下一个广告内容，默认不换 
     */
    showBanner(position: BannerPos, loadNewAD = false) {
        if (SDKManager.disableAllADAfter5Shares) {
            console.log('玩家已分享5次,不再显示Banner广告')
            return;
        }
        super.showBanner(position);
        let tt = JSBridge.getTTObj();
        if (!tt) return;
        console.log('显示头条Banner: ' + this.bannerAd);
        if (SDKManager.closeBannerTimes > MaxCloseBannerTimes) {
            console.log('玩家已经关闭' + MaxCloseBannerTimes + '次头条Banner，不能再显示了');
            return;
        }
        let bannerAd = this.bannerAd;
        if (bannerAd && loadNewAD) {
            bannerAd.destroy();
            bannerAd = this.bannerAd = null;
        }
        if (!bannerAd) {
            console.log('this.bannerAdId: ' + QuLe.instance.remoteConfig.bannerId);
            let pos: any = this.getLeftTopValues(tt, position);
            bannerAd = this.bannerAd = tt.createBannerAd({
                adUnitId: QuLe.instance.remoteConfig.bannerId,
                style: {
                    left: pos.left,
                    top: pos.top,
                    width: this.bannerAdWidth
                }
            });
            bannerAd.onResize(res => {
                let pos: any = this.getLeftTopValues(tt, this.currPosition);
                bannerAd.style.left = pos.left;
                bannerAd.style.top = pos.top;
            })
            bannerAd.onLoad(() => {
                console.log('头条Banner加载成功');
                bannerAd.show();
                QuLe.instance.record(QuLe.PlatTouTiao, ADType.Banner);
            })
            bannerAd.onError((err) => {
                console.log('头条Banner加载失败：' + JSON.stringify(err));
                bannerAd.destroy();
                bannerAd = this.bannerAd = null;
            })
        }
        bannerAd.show();
    }

    /** 设置Banner广告位置 */
    setBannerPos(position: BannerPos) {
        if (SDKManager.disableAllADAfter5Shares) {
            console.log('玩家已分享5次,不再显示Banner广告')
            return;
        }
        super.setBannerPos(position);
        let tt = JSBridge.getTTObj();
        let bannerAd = this.bannerAd;
        if (!tt || !bannerAd) return;
        let pos: any = this.getLeftTopValues(tt, position);
        bannerAd.style.left = pos.left;
        bannerAd.style.top = pos.top;
    }

    private getLeftTopValues(tt: any, position: BannerPos) {
        let info = tt.getSystemInfoSync();
        console.log('屏幕尺寸：' + JSON.stringify(info))
        let iphoneXLiuHaiSize = info.screenWidth * 0.05;
        let left = 0, top = 0;
        switch (position) {
            case BannerPos.TopLeft:
                left = iphoneXLiuHaiSize;
                top = 0;
                break;
            case BannerPos.TopCenter:
                left = (info.screenWidth - this.bannerAdWidth) * 0.5;
                top = 0;
                break;
            case BannerPos.TopRight:
                left = info.screenWidth - this.bannerAdWidth - iphoneXLiuHaiSize;
                top = 0;
                break;
            case BannerPos.BottomLeft:
                left = iphoneXLiuHaiSize;
                top = info.screenHeight - (this.bannerAdWidth / 16) * 9;
                break;
            case BannerPos.BottomCenter:
                left = (info.screenWidth - this.bannerAdWidth) * 0.5;
                top = info.screenHeight - (this.bannerAdWidth / 16) * 9;
                break;
            case BannerPos.BottomRight:
                left = info.screenWidth - this.bannerAdWidth - iphoneXLiuHaiSize;
                top = info.screenHeight - (this.bannerAdWidth / 16) * 9;
                break;
        }
        return { left: left, top: top }
    }

    /** 隐藏Banner广告 */
    hideBanner(byPlayerClick: boolean) {
        super.hideBanner(byPlayerClick);
        let bannerAd = this.bannerAd;
        console.log('隐藏头条Banner: ' + bannerAd);
        if (bannerAd) {
            bannerAd.hide();
            if (byPlayerClick) {
                SDKManager.closeBannerTimes += 1;
            }
        }
    }

    /** 显示激励视频//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     * @param onClose 返回是否观看完成的布尔值
     */
    showRewardVideo(onClose: Function) {
        let tt = JSBridge.getTTObj();
        if (!tt) {
            onClose && onClose(false);
            return;
        }
        super.showRewardVideo(onClose);
        this.onVideoClose = onClose;
        let videoAd = this.videoAd;
        this.isListenVideoShow = true;
        if (!videoAd) {
            console.log('创建头条视频广告对像');
            videoAd = this.videoAd = tt.createRewardedVideoAd({ adUnitId: QuLe.instance.remoteConfig.videoId });
            videoAd.onLoad(() => {
                console.log('头条视频广告加载成功');
            })
            videoAd.onClose((res) => {
                console.log('头条视频广告关闭了：' + JSON.stringify(res));
                if (this.onVideoClose) {
                    this.onVideoClose(res.isEnded);
                }
            })
            videoAd.onError((err) => {
                console.log('头条视频广告加载失败：' + JSON.stringify(err));
                if (this.onVideoClose) {
                    this.onVideoClose(false);
                }
            })
        }
        videoAd.show().then(() => {
            console.log("头条视频广告显示成功：");
            if (this.isListenVideoShow) {
                QuLe.instance.record(QuLe.PlatTouTiao, ADType.Video);
                this.isListenVideoShow = false;
            }
        }).catch(err => {
            console.log("头条视频广告显示失败：" + JSON.stringify(err) + ', 尝试重新加载一遍再显示');
            // 可以尝试再加载一次
            videoAd.load().then(() => {
                return videoAd.show().catch(err => {
                    console.log("头条视频广告尝试重新显示仍旧失败：" + JSON.stringify(err));
                    if (this.onVideoClose) {
                        this.onVideoClose(false);
                    }
                });
            });
        });
    }

    /** 显示插屏广告（插屏广告仅今日头条安卓客户端支持）//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     * 暂时不支持onError回调，故干脆不做任何回调，考虑官港SDK有Bug，后陆再添加
     */
    showInsertAD(onClose: Function) {
        let tt = JSBridge.getTTObj();
        if (tt && SDKManager.disableAllADAfter5Shares) {
            console.log('玩家已分享5次,不再显示插屏广告')
            onClose && onClose();
            return;
        }
        super.showInsertAD(onClose);
        this.onInsertADClose = onClose;
        let insertAD = this.insertAD;
        if (!insertAD) {
            insertAD = this.insertAD = tt.createInterstitialAd({ adUnitId: QuLe.instance.remoteConfig.insertId });
            insertAD.onLoad(() => {
                QuLe.instance.record(QuLe.PlatTouTiao, ADType.Insert);
                console.log('头条插屏广告加载成功');
            })
            insertAD.onClose(() => {
                console.log('头条插屏广告关闭了');
                this.onInsertADClose && this.onInsertADClose();
            })
            insertAD.onError((err) => {
                console.error('头条插屏广告加载失败1：' + JSON.stringify(err));
                this.onInsertADClose && this.onInsertADClose();
            })
        }
        insertAD.load().then(() => {
            try {
                insertAD.show();
            } catch (err) {
                console.error('头条插屏广告加载失败2：' + JSON.stringify(err));
                this.onInsertADClose && this.onInsertADClose();
            }
        });
    }

}
